﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace LEET.Application
{
    public class LEETTestResult
    {
        private IList<KeyValuePair<String, int>> scriptLineErrors;

        internal string errormsg;
        internal string outputmsg;

        public LEETTestResult(String output, String errors)
        {
            scriptLineErrors = new List<KeyValuePair<String, int>>();
            Failed = false;
            errormsg = errors;
            outputmsg = output;
            String str = errors + output;
            if (str.Length > 0)
            {
                Failed = true;
                StringReader reader = new StringReader(str);
                String line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Contains("on line:"))
                    {
                        line = line.Substring(4);
                        String[] split = line.Split(new string [] {"on line:"}, StringSplitOptions.None);
                        string [] nameSplit = split[0].Split('.');
                        string lineNum = split[1];
                        scriptLineErrors.Add(new KeyValuePair<string, int>(nameSplit[nameSplit.Length - 1].Trim(), Int32.Parse(lineNum)));
                    }
                }
            }
            //"\nUnhandled Exception: System.Exception: ID:\r\n The system cannot find the file specified\r\n\tat Compiled_Tests.CalcCwithLeet on line: 2\r\n\r\n   at Compiled_Tests.BaseController.FireEvent(IAutomationActionResult result)\r\n   at Compiled_Tests.BaseController.Run()\r\n   at Compiled_Tests.CalcCwithLeet.Main()\n"
        }
        

        public bool Failed { get; private set; }

        internal int FailingLine(string currentScriptName)
        {
            foreach (KeyValuePair<string, int> pair in scriptLineErrors)
                if (pair.Key.ToLower().Equals(currentScriptName.ToLower()))
                    return pair.Value;
            throw new ArgumentException("ScriptName not present in error trace: \r\n" + errormsg);
        }
    }
}
